/**
 * Vite 完整配置
 * 包含路径别名、API代理、开发服务器、构建优化等
 */

import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { resolve } from 'path';
import { createHtmlPlugin } from 'vite-plugin-html';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import { viteMockServe } from 'vite-plugin-mock';
import { visualizer } from 'rollup-plugin-visualizer';
import { VitePWA } from 'vite-plugin-pwa';
import legacy from '@vitejs/plugin-legacy';
import { createStyleImportPlugin } from 'vite-plugin-style-import';
import { createProxy } from './src/utils/proxy';

export default defineConfig(({ command, mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '');
  const isProduction = command === 'build';
  const isDevelopment = !isProduction;

  return {
    // 基础配置
    base: env.VITE_BASE_URL || '/',
    
    // 路径别名配置
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
        '@components': resolve(__dirname, 'src/components'),
        '@views': resolve(__dirname, 'src/views'),
        '@utils': resolve(__dirname, 'src/utils'),
        '@assets': resolve(__dirname, 'src/assets'),
        '@styles': resolve(__dirname, 'src/styles'),
        '@api': resolve(__dirname, 'src/api'),
        '@store': resolve(__dirname, 'src/store'),
        '@router': resolve(__dirname, 'src/router'),
        '@config': resolve(__dirname, 'src/config'),
        '@types': resolve(__dirname, 'src/types'),
        '@hooks': resolve(__dirname, 'src/hooks'),
        '@constants': resolve(__dirname, 'src/constants'),
        '@services': resolve(__dirname, 'src/services'),
        '@middleware': resolve(__dirname, 'src/middleware'),
        '@directives': resolve(__dirname, 'src/directives'),
        '@filters': resolve(__dirname, 'src/filters'),
        '@mixins': resolve(__dirname, 'src/mixins'),
        '@plugins': resolve(__dirname, 'src/plugins'),
        '@tests': resolve(__dirname, 'src/tests'),
        '@mocks': resolve(__dirname, 'src/mocks'),
        '@locales': resolve(__dirname, 'src/locales'),
        '@themes': resolve(__dirname, 'src/themes'),
        '@layouts': resolve(__dirname, 'src/layouts'),
        '@modules': resolve(__dirname, 'src/modules'),
        '@pages': resolve(__dirname, 'src/pages'),
        '@widgets': resolve(__dirname, 'src/widgets'),
        '@features': resolve(__dirname, 'src/features'),
        '@shared': resolve(__dirname, 'src/shared'),
        '@core': resolve(__dirname, 'src/core'),
        '@app': resolve(__dirname, 'src/app'),
        '@public': resolve(__dirname, 'public'),
        '@node_modules': resolve(__dirname, 'node_modules')
      }
    },

    // 插件配置
    plugins: [
      // Vue 支持
      vue({
        template: {
          compilerOptions: {
            preserveWhitespace: false
          }
        }
      }),

      // Vue JSX 支持
      vueJsx(),

      // HTML 模板处理
      createHtmlPlugin({
        minify: isProduction,
        inject: {
          data: {
            title: env.VITE_APP_TITLE || 'Vite App',
            description: env.VITE_APP_DESCRIPTION || 'A Vite App',
            keywords: env.VITE_APP_KEYWORDS || 'vite,vue,typescript'
          }
        }
      }),

      // SVG 图标支持
      createSvgIconsPlugin({
        iconDirs: [resolve(__dirname, 'src/assets/icons')],
        symbolId: 'icon-[dir]-[name]'
      }),

      // Mock 数据支持
      viteMockServe({
        mockPath: 'mock',
        localEnabled: isDevelopment,
        prodEnabled: false,
        injectCode: `
          import { setupProdMockServer } from './mock/_createProductionServer';
          setupProdMockServer();
        `
      }),

      // PWA 支持
      VitePWA({
        registerType: 'autoUpdate',
        workbox: {
          globPatterns: ['**/*.{js,css,html,ico,png,svg}']
        },
        includeAssets: ['favicon.ico', 'apple-touch-icon.png', 'masked-icon.svg'],
        manifest: {
          name: env.VITE_APP_TITLE || 'Vite App',
          short_name: 'Vite App',
          description: env.VITE_APP_DESCRIPTION || 'A Vite App',
          theme_color: '#ffffff',
          background_color: '#ffffff',
          display: 'standalone',
          icons: [
            {
              src: 'pwa-192x192.png',
              sizes: '192x192',
              type: 'image/png'
            },
            {
              src: 'pwa-512x512.png',
              sizes: '512x512',
              type: 'image/png'
            }
          ]
        }
      }),

      // 样式按需导入
      createStyleImportPlugin({
        resolves: [
          {
            libraryName: 'ant-design-vue',
            esModule: true,
            resolveStyle: (name) => {
              return `ant-design-vue/es/${name}/style/css`;
            }
          }
        ]
      }),

      // 兼容性支持
      legacy({
        targets: ['defaults', 'not IE 11'],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
        renderLegacyChunks: true,
        polyfills: [
          'es.symbol',
          'es.array.filter',
          'es.promise',
          'es.promise.finally',
          'es/map',
          'es/set',
          'es.array.for-each',
          'es.object.define-properties',
          'es.object.get-own-property-descriptor',
          'es.object.get-own-property-descriptors',
          'es.object.keys',
          'es.object.to-string',
          'web.dom-collections.for-each',
          'esnext.global-this',
          'esnext.string.match-all'
        ]
      }),

      // 构建分析
      ...(isProduction ? [
        visualizer({
          filename: 'dist/stats.html',
          open: true,
          gzipSize: true,
          brotliSize: true
        })
      ] : [])
    ],

    // CSS 配置
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `
            @import "@/styles/variables.scss";
            @import "@/styles/mixins.scss";
          `,
          charset: false
        },
        less: {
          modifyVars: {
            // 自定义主题变量
            '@primary-color': '#1890ff',
            '@link-color': '#1890ff',
            '@border-radius-base': '4px'
          },
          javascriptEnabled: true,
          charset: false
        }
      },
      postcss: {
        plugins: [
          require('autoprefixer'),
          require('postcss-preset-env')
        ]
      }
    },

    // 开发服务器配置
    server: {
      port: 3000,
      host: '0.0.0.0',
      open: true,
      cors: true,
      strictPort: false,
      
      // API 代理配置
      proxy: {
        // 通用API代理
        '/api': {
          target: env.VITE_API_BASE_URL || 'http://localhost:8080',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api/, '/api'),
          configure: (proxy, options) => {
            proxy.on('proxyReq', (proxyReq, req, res) => {
              console.log(`[PROXY] ${req.method} ${req.url} -> ${proxyReq.path}`);
            });
            proxy.on('proxyRes', (proxyRes, req, res) => {
              console.log(`[PROXY] ${req.method} ${req.url} -> ${proxyRes.statusCode}`);
            });
          }
        },

        // 用户服务代理
        '/api/user': {
          target: env.VITE_USER_API_URL || 'http://localhost:8081',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api\/user/, '/user')
        },

        // 商品服务代理
        '/api/product': {
          target: env.VITE_PRODUCT_API_URL || 'http://localhost:8082',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api\/product/, '/product')
        },

        // 订单服务代理
        '/api/order': {
          target: env.VITE_ORDER_API_URL || 'http://localhost:8083',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api\/order/, '/order')
        },

        // 文件上传代理
        '/api/upload': {
          target: env.VITE_UPLOAD_API_URL || 'http://localhost:8084',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/api\/upload/, '/upload')
        },

        // WebSocket 代理
        '/ws': {
          target: env.VITE_WS_URL || 'ws://localhost:8085',
          ws: true,
          changeOrigin: true,
          secure: false
        },

        // 第三方API代理
        '/api/external': {
          target: env.VITE_EXTERNAL_API_URL || 'https://api.external.com',
          changeOrigin: true,
          secure: true,
          rewrite: (path) => path.replace(/^\/api\/external/, ''),
          headers: {
            'Authorization': `Bearer ${env.VITE_EXTERNAL_API_TOKEN || 'your-token-here'}`
          }
        },

        // 动态代理配置
        ...createProxy(env)
      }
    },

    // 构建配置
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      sourcemap: !isProduction,
      
      // 资源内联阈值
      assetsInlineLimit: 4096,
      
      // 代码分割
      rollupOptions: {
        input: {
          main: resolve(__dirname, 'index.html')
        },
        output: {
          // 静态资源分类
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: (assetInfo) => {
            const info = assetInfo.name.split('.');
            const ext = info[info.length - 1];
            if (/\.(css)$/.test(assetInfo.name)) {
              return `css/[name]-[hash].${ext}`;
            }
            if (/\.(png|jpe?g|gif|svg|webp|avif)$/.test(assetInfo.name)) {
              return `images/[name]-[hash].${ext}`;
            }
            if (/\.(woff|woff2|eot|ttf|otf)$/.test(assetInfo.name)) {
              return `fonts/[name]-[hash].${ext}`;
            }
            if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)$/.test(assetInfo.name)) {
              return `media/[name]-[hash].${ext}`;
            }
            return `assets/[name]-[hash].${ext}`;
          },
          
          // 手动代码分割
          manualChunks: {
            // Vue 相关
            vue: ['vue', 'vue-router', 'vuex'],
            
            // UI 库
            'ant-design-vue': ['ant-design-vue'],
            'element-plus': ['element-plus'],
            
            // 工具库
            utils: ['lodash', 'dayjs', 'axios'],
            
            // 图表库
            charts: ['echarts', 'chart.js'],
            
            // 编辑器
            editor: ['monaco-editor', 'codemirror']
          }
        }
      },
      
      // 压缩配置
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: isProduction,
          drop_debugger: isProduction,
          pure_funcs: isProduction ? ['console.log'] : []
        },
        mangle: {
          safari10: true
        }
      },
      
      // 构建优化
      chunkSizeWarningLimit: 1000,
      reportCompressedSize: false
    },

    // 预览服务器配置
    preview: {
      port: 4173,
      host: '0.0.0.0',
      open: true,
      cors: true
    },

    // 依赖优化
    optimizeDeps: {
      include: [
        'vue',
        'vue-router',
        'vuex',
        'axios',
        'lodash',
        'dayjs',
        'ant-design-vue',
        'element-plus'
      ],
      exclude: ['@vueuse/core']
    },

    // 环境变量
    define: {
      __VUE_OPTIONS_API__: true,
      __VUE_PROD_DEVTOOLS__: false,
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: false
    },

    // 实验性功能
    experimental: {
      renderBuiltUrl(filename, { hostType }) {
        if (hostType === 'js') {
          return { js: `/${filename}` };
        } else {
          return { relative: true };
        }
      }
    }
  };
});
